import { extend } from 'umi-request';
import { getDvaApp,history } from 'umi';
import { message, notification, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { getToken } from '@/utils/auth';
import errorCode from '@/utils/errorCode';
const { confirm } = Modal;

const request = extend({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

request.interceptors.request.use((url, options) => {
  const isToken = (options.headers || {}).isToken === false;
  if (getToken() && !isToken) {
    options.headers['Authorization'] = 'Bearer ' + getToken()
  }
  return {
    url: `${url}`,
    options: {
      ...options,
      interceptors: true,
    },
  };
});

// 响应拦截器
request.interceptors.response.use(async(res) => {
  const code = res.status;
  const msg = errorCode[code] || errorCode['default'];

  if (code === 401) {
    confirm({
      title: '系统提示',
      icon: <ExclamationCircleOutlined />,
      content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
      cancelText: '取消',
      okText: '确定',
      onOk() {
        getDvaApp()
          ._store.dispatch({
            type: 'logins/logout',
          })
          .then(() => {
            // window.location = '/login'
            history.push('/login')
          });
      },
      onCancel() {
        console.log('重新登录');
      },
    });
  } else if (code === 500) {
    //已验证此状态
    message.error(msg);
    return Promise.reject(new Error(msg));
  } else if (code !== 200) {
    confirm({
      title: '系统提示',
      icon: <ExclamationCircleOutlined />,
      content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
      cancelText: '取消',
      okText: '确定',
      onOk() {
        getDvaApp()
          ._store.dispatch({
            type: 'logins/logout',
          })
          .then(() => {
            history.push('/login')
          });
      },
      onCancel() {
        console.log('重新登录');
      },
    });

  } else {
    return res;
  }
});

// error => {
//   console.log('err' + error);
//   let { msg } = error;
//   if (msg == 'Network Error') {
//     msg = '后端接口连接异常';
//   } else if (msg.includes('timeout')) {
//     msg = '系统接口请求超时';
//   } else if (msg.includes('Request failed with status code')) {
//     msg = '系统接口' + msg.substr(msg.length - 3) + '异常';
//   }
//   message.error(msg);
//   return Promise.reject(error);
// },

export default request;
